package com.padgett.resourcemanagement.invoice;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Save invoice.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxSaveInvoiceServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxSaveInvoiceServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String invoiceId=req.getParameter("invoiceId");
		String invoiceNumber=req.getParameter("InvoiceNumber");
		String issuedDateString=req.getParameter("IssuedDate");
		String accountant=req.getParameter("Accountant");
		String note=req.getParameter("Note");
		// Client Number and Legal Number must be presented to generate a unique key
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		
		Key key=KeyFactory.stringToKey(invoiceId);
		Entity invoice=ClientDAO.loadEntity(key);
		invoice.setProperty("LastModifiedBy", user.getNickname());
		invoice.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));

		invoice.setProperty("InvoiceNumber", Long.parseLong(invoiceNumber));
		invoice.setProperty("Accountant", accountant);
		Date issuedDate=null;
		if(issuedDateString!=null&&!issuedDateString.isEmpty()){
			issuedDate=new Date(Long.parseLong(issuedDateString));
			invoice.setProperty("IssuedDate", issuedDate);
		}
		if(note!=null){
			invoice.setUnindexedProperty("Note", new Text(note));
		}
		Key savedKey=ClientDAO.saveEntity(invoice);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("invoiceId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save client at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
